<script lang="ts" setup>
import { onActivated, ref } from 'vue';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { dialog } from '@/settings/components/dialog';
import { useAppStore } from '@/settings/stores';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const loading = ref(false);
const formData = ref<Record<string, any>>({
  commIllustrate: '',
  communityCode: '',
  communityHeadPic: '',
  communityId: '',
  communityLogo: '',
  communityName: '',
  communityPic: '',
  atomgitPopCommunityMediumVOList: [],
  applyToJoin: 1,
});
const formRef = ref<FormInstance>();
const { success } = useNotification();
const appStore = useAppStore();
const footerListing = ref<Record<string, any>[]>([]);

const submit = async () => {
  const res = await formRef.value?.validate();

  if (res) {
    return;
  }

  const data: Record<string, any> = {
    ...formData.value,
    atomgitPopCommunityMediumDTOList: formData.value.atomgitPopCommunityMediumVOList,
  };

  delete data.atomgitPopCommunityMediumVOList;

  saveFooter();

  const { isSuccess } = await $fetch('/admin/community/editCommunity', {
    method: 'post',
    data,
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
    getDetail();
    appStore.fetchConfig();
  }
};

const saveFooter = async () => {
  const { isSuccess } = await $fetch('/admin/footer/batchUpdatesFooter', {
    method: 'post',
    data: {
      atomgitPopFooterUpdateDTOList: footerListing.value.map(item => ({
        id: item.id,
        footerContent: item.footerContent,
        isDelete: item.isDelete,
      })),
    },
  });

  if (isSuccess) {
    getFooter();
  }
};

const getDetail = async () => {
  const { isSuccess, data } = await $fetch('/admin/community/getCommunityInfo', {
    loadingStatus: loading,
  });

  if (isSuccess) {
    formData.value = {
      commIllustrate: data.commIllustrate,
      communityCode: data.communityCode,
      communityHeadPic: data.communityHeadPic,
      communityId: data.communityId,
      communityLogo: data.communityLogo,
      communityName: data.communityName,
      communityPic: data.communityPic,
      atomgitPopCommunityMediumVOList: data.atomgitPopCommunityMediumVOList,
      applyToJoin: data.applyToJoin,
    };
  }
}

const addMedium = async () => {
  const { button, data } = await dialog(() => import('./add-edit-medium-window.vue'), {
    title: t('settings.view.general.addmedium'),
  });

  if (button == 'ok') {
    formData.value.atomgitPopCommunityMediumVOList.push({
      mediumJumpAddress: data.url,
      mediumName: data.name,
      mediumPic: data.pic,
      isDelete: 2,
    });
  }
}

const editMedium = async (item: Record<string, any>) => {
  const { button, data } = await dialog(() => import('./add-edit-medium-window.vue'), {
    title: t('settings.view.general.editmedium'),
    props: {
      url: item.mediumJumpAddress,
      name: item.mediumName,
      pic: item.mediumPic,
    },
  });

  if (button == 'ok') {
    item.mediumJumpAddress = data.url;
    item.mediumName = data.name;
    item.mediumPic = data.pic;
  }
};

const addFooter = async () => {
  const { button, data } = await dialog(() => import('./add-edit-footer-window.vue'), {
    title: t('settings.view.general.addfooter'),
  });

  if (button == 'ok') {
    footerListing.value.push({
      footerContent: data.content,
    });
  }
}

const editFooter = async (item: Record<string, any>) => {
  const { button, data } = await dialog(() => import('./add-edit-footer-window.vue'), {
    title: t('settings.view.general.editfooter'),
    props: {
      id: item.id,
      content: item.footerContent,
    },
  });

  if (button == 'ok') {
    item.footerContent = data.content;
  }
};

const getFooter = async () => {
  const { isSuccess, data } = await $fetch('/admin/footer/getFooterPageList', {
    method: 'post',
    data: {
      pageNum: 1,
      pageSize: 1000,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    footerListing.value = data.records;
  }
}

onActivated(() => {
  getDetail();
  getFooter();
});
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData" @submit="submit" v-confirm>
        <AFormItem :label="$t('settings.view.general.column1')" field="communityName" :rules="[{ required: true, message: $t('settings.notification.required') }]">
          <AInput v-model="formData.communityName" :max-length="50" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.general.column2')" field="commIllustrate" :rules="[{ required: true, message: $t('settings.notification.required') }]">
          <ATextarea v-model="formData.commIllustrate" :max-length="500" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.general.column4')" field="communityLogo" :rules="[{ required: true, message: $t('settings.notification.required') }]" :help="$t('settings.view.general.help4')">
          <OpenUpload v-model="formData.communityLogo" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.general.column5')" field="communityHeadPic" :rules="[{ required: true, message: $t('settings.notification.required') }]" :help="$t('settings.view.general.help5')">
          <OpenUpload v-model="formData.communityHeadPic" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.general.column6')" field="communityPic" :help="$t('settings.view.general.help6')">
          <OpenUpload v-model="formData.communityPic" />
        </AFormItem>

        <!-- <AFormItem label="是否允许加入" field="applyToJoin">
          <ASwitch v-model="formData.applyToJoin" :checked-value="1" :unchecked-value="2">
            <template #checked>
              允许
            </template>
            <template #unchecked>
              不允许
            </template>
          </ASwitch>
        </AFormItem> -->

        <AFormItem :label="$t('settings.view.general.column7')" field="atomgitPopCommunityMediumVOList">
          <ASpace direction="vertical" fill>
            <AList size="small">
              <AListItem v-for="(item, index) in formData.atomgitPopCommunityMediumVOList" :key="item.operatorId">
                <AListItemMeta :title="item.mediumName" :description="item.mediumJumpAddress" class="mr-32">
                  <template #avatar>
                    <img class="size-20 object-cover" :alt="item.mediumName" :src="item.mediumPic">
                  </template>
                </AListItemMeta>

                <template #actions>
                  <IconEdit @click="editMedium(item)" />
                  <IconDelete @click="formData.atomgitPopCommunityMediumVOList.splice(index, 1)" v-if="item.isDelete == 2" />
                </template>
              </AListItem>
            </AList>

            <AButton size="small" @click="addMedium">{{ $t('settings.view.general.add') }}</AButton>
          </ASpace>
        </AFormItem>

        <AFormItem label="Footer">
          <ASpace direction="vertical" fill>
            <AList size="small">
              <template v-for="(item, index) in footerListing" :key="`${item.id}-${index}`">
                <AListItem v-if="item.isDelete !== 0">
                  <AListItemMeta :description="item.footerContent" class="mr-32" />

                  <template #actions>
                    <IconEdit @click="editFooter(item)" />
                    <IconDelete @click="item.isDelete = 0" />
                  </template>
                </AListItem>
              </template>
            </AList>

            <AButton size="small" @click="addFooter">{{ $t('settings.view.general.add') }}</AButton>
          </ASpace>
        </AFormItem>

        <ADivider />

        <AFormItem>
          <ASpace>
            <AButton html-type="submit" type="primary" :loading="loading">{{ $t('settings.action.submit') }}</AButton>
          </ASpace>
        </AFormItem>
      </AForm>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
